package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserMapper;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl implements UserService {


    //分页查询
    @Override
    public PageInfo<User> findByPage(int pageNum, int pageSize) {
        //1.调用工具类,创建代理对象
        SqlSession sqlSession = MyBatisUtils.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //2.业务处理
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userMapper.findAll();
        //3.释放资源
        MyBatisUtils.release(sqlSession);

        return new PageInfo<>(list);
    }

    //添加记录
    @Override
    public void save(User user) {
        //1.通过工具类创建代理对象
        SqlSession sqlSession = MyBatisUtils.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //2.业务处理
        userMapper.save(user);
        //3.释放资源
        MyBatisUtils.release(sqlSession);


    }

    //删除记录
    @Override
    public void deleteUser(String id) {
        //1.通过工具类创建代理对象
        SqlSession sqlSession = MyBatisUtils.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //2.业务处理
        userMapper.deleteUser(id);
        //3.释放资源
        MyBatisUtils.release(sqlSession);
    }

    //更新记录
    @Override
    public void update(User user) {
        //1.通过工具类创建对象
        SqlSession sqlSession = MyBatisUtils.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //2.业务处理
        userMapper.update(user);
        //3.释放资源
        MyBatisUtils.release(sqlSession);
    }
}
